package org.cloud.scheduler.converter;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.cloud.common.util.StringUtils;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

/**
 * String转换为字符串集合形式转换器，待转换的字符串使用,分隔
 * @author wangyuan
 * @since 2019年7月7日 下午3:54:35
 *
 */
public class StringToLongListConverter implements ConditionalGenericConverter {

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		if(source == null) {
			return null;
		}
		String sourceStr = (String) source;
		if(StringUtils.isEmpty(sourceStr)) {
			return null;
		}
		
		String[] sourceArr = sourceStr.split(",");
		if(sourceArr == null || sourceArr.length == 0) {
			return null;
		}
		
		List<Long> result = new ArrayList<>();
		for(String item : sourceArr) {
			result.add(Long.valueOf(item));
		}
		
		return result;
	}

	@Override
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
		if(String.class.equals(sourceType.getType()) && List.class.equals(targetType.getType())) {
			ResolvableType resolvableType = targetType.getResolvableType();
			if(resolvableType == null) {
				return false;
			}
			
			ResolvableType genericClazz = resolvableType.getGeneric(0);
			if(Long.class.equals(genericClazz.resolve())) {
				return true;
			}
		}
		return false;
	}

}
